<template>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="姓名:" prop="leaveName">
            <el-input v-model="ruleForm.leaveName" disabled />
        </el-form-item>
        <el-form-item label="部门:" prop="departId">
            <el-select v-model="ruleForm.departId" placeholder="请选择部门" disabled>
                <el-option label="IT信息部" :value="1" />
                <el-option label="人力资源部" :value="2" />
                <el-option label="财务部" :value="3" />
                <el-option label="销售部" :value="4" />
                <el-option label="行政部" :value="5" />
            </el-select>
        </el-form-item>
        <el-form-item label="请假类别:">
            <el-radio-group v-model="ruleForm.leaveType">
                <el-radio :value="1">事假</el-radio>
                <el-radio :value="2">病假</el-radio>
                <el-radio :value="3">婚假</el-radio>
                <el-radio :value="4">丧假</el-radio>
                <el-radio :value="5">产假</el-radio>
                <el-radio :value="6">补休</el-radio>
                <el-radio :value="7">工伤</el-radio>
                <el-radio :value="8">其他</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="请假时间:" required>
            <div class="demo-date-picker">
                <div class="block">
                    <el-date-picker type="datetimerange" range-separator="到" start-placeholder="开始时间"
                        end-placeholder="结束时间" :size="size" v-model="datatime" @change="handleDateChange"
                        :picker-options="pickerOptions"  />
                </div>
            </div>
        </el-form-item>
        <el-form-item label="总工时:" prop="totalHours">
            <el-input v-model="ruleForm.totalHours" />
        </el-form-item>
        <el-form-item label="请假事由:" prop="cause">
            <el-input v-model="ruleForm.cause" type="textarea" />
        </el-form-item>
        <el-form-item label="部门领导:">
            <el-input v-model="depName.value" disabled />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                提交
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
import {read,write} from '@/axios/axiosHelper'

const store = useCounterStore();

const datatime = ref<any>([]); //定义一个空数组来接收数据

const size = ref<'default' | 'large' | 'small'>('default')

interface RuleForm {
    operatorId: number,
    leaveName: string,
    departId: number,
    leaveType: string,
    leaveCreateTime: string,
    coverageTime: string,
    totalHours: string,
    cause: string,
    departmentHeads: string,
    appstatus: string
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    operatorId: store.counterStore.userId,
    leaveName: store.counterStore.userName,
    departId: store.counterStore.departmentId,
    leaveType: "",
    leaveCreateTime: "",
    coverageTime: "",
    totalHours: "",
    cause: "",
    departmentHeads: "3",
    appstatus: "100"
})

const depName = reactive<any>([])   
depName.value = "WW";

const rules = reactive<FormRules<RuleForm>>({
    leaveName: [
        { required: true, message: '请输入申请人', trigger: 'blur' },
    ],
    coverageTime: [
        {
            required: true,
            message: '请选择时间范围',
            trigger: 'change',
        },
    ],
    totalHours: [
        {
            required: true,
            message: '请输入总工时',
            trigger: 'change',
        },
    ],
    cause: [
        { required: true, message: '请输入请假事由', trigger: 'blur' },
        { max: 140, message: '长度限制140个字符', trigger: 'blur' },
    ],
    departmentHeads: [
        {
            required: true,
            message: '请输入部门领导',
            trigger: 'change',
        },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('添加数据', ruleForm)    ;
            write.post("/write/api/Leave/Handle", ruleForm).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("添加成功")
                }
                else {
                    ElMessage.error("添加失败")
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const handleDateChange = (value: any[]) => {
    if (value.length === 2) {
        const startDate = new Date(value[0]);
        const endDate = new Date(value[1]);

        let totalHours = 0;
        // 克隆开始日期和结束日期，避免修改原始日期对象
        let currentDate = new Date(startDate);
        const endOfDay = new Date(endDate);
        endOfDay.setHours(17, 0, 0, 0);

        while (currentDate <= endOfDay) {
            const currentStart = new Date(currentDate);
            currentStart.setHours(9, 0, 0, 0);
            const currentEnd = new Date(currentDate);
            currentEnd.setHours(17, 0, 0, 0);

            // 计算当前日期的开始时间和结束时间
            const actualStart = currentDate > currentStart ? currentDate : currentStart;
            const actualEnd = endDate < currentEnd ? endDate : currentEnd;

            // 计算当前日期的工作时长
            const timeDiff = actualEnd.getTime() - actualStart.getTime();
            if (timeDiff > 0) {
                totalHours += timeDiff / (1000 * 60 * 60);
            }

            // 移动到下一天
            currentDate.setDate(currentDate.getDate() + 1);
        }

        // 按照一天8小时来计算总工时
        totalHours = Math.min(totalHours, 8 * Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)));

        // 去除小数点，向下取整
        totalHours = Math.floor(totalHours);

        // 将结果赋值给 ruleForm.totalHours
        ruleForm.totalHours = totalHours.toString(); 

        // 同时将日期赋值给 ruleForm 的对应字段
        ruleForm.leaveCreateTime = value[0];
        ruleForm.coverageTime = value[1];
    }
}

// 定义时间选择器的选项
const pickerOptions = {
    selectableRange: '09:00:00 - 17:00:00'
}
</script>